package my.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import my.springboot.domain.primary.Dict;
import my.springboot.mapper.DictMapper;
import my.springboot.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

import static my.springboot.common.Constant.DICT_KEY;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author fengbo
 * @since 2019-09-17
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<Dict> getDictList(String paramKey) {
        if (StringUtils.isEmpty(paramKey)) {
            return Collections.emptyList();
        }
        String key = String.format(DICT_KEY, paramKey);
        String value = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(value)) {
            return JSON.parseArray(value, Dict.class);
        }
        List<Dict> list = list(new QueryWrapper<Dict>().lambda().eq(Dict::getParentKey, paramKey));
        String str = JSON.toJSONString(list);
        redisTemplate.opsForValue().set(key, str);
        return list;
    }
}
